package com.demo.dao.custom;

import com.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by Administrator on 2017/2/13 0013.
 */
@Repository
public class UserDaoImpl implements UserDaoCustom {
  @Autowired
  private EntityManager entityManager;

  @Override
  public Page<User> findAllCustom(Pageable pageable) {
    Query query = entityManager.createQuery("select u from User u left join fetch u.roles r");
    List resultList = query.setMaxResults(pageable.getPageSize()).setFirstResult((pageable.getPageNumber()) * pageable.getPageSize()).getResultList();
    long resultCount = (long) entityManager.createQuery("select count(u.id) from User u").getSingleResult();
    return new PageImpl(resultList, pageable, resultCount);
  }
}
